<template>
  <form-dialog
    ref="formDrawerRef"
    top="2vh"
    width="98%"
    :destroyOnClose="true"
    @submit="handleSubmitCar"
  >
    <template #header>
      <span class="mr-12 text-[18px]">完善信息</span>
      <el-date-picker
        v-model="curYear"
        type="year"
        :clearable="false"
        placeholder="选择年份"
        @change="handleChangeYear"
      />
      <el-button type="primary" class="ml-10" :loading="isLoading" @click="handleArchiveCar"
        >归档</el-button
      >
    </template>
    <div class="dialog-body">
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
        <el-row :gutter="20">
          <el-divider content-position="left">车辆信息</el-divider>
          <template v-for="item in formConfigList" :key="item.prop">
            <el-col v-if="item.isShow" :span="item.span">
              <el-form-item :label="item.label" :prop="item.prop">
                <upload-img
                  :limit="item.limit"
                  :disabled="item.disabled"
                  :imgList="form[item.prop]"
                  @success="handleUpdateImg($event, item.prop)"
                ></upload-img>
              </el-form-item>
            </el-col>
          </template>
          <el-divider content-position="left">交通事故记录</el-divider>
          <el-col :span="24">
            <el-form-item>
              <template #label>
                <el-button type="primary" size="small" @click="handleAddTraffic">添加</el-button>
              </template>
              <record-list
                :tableData="form.accidentRecordAddList"
                @updateImg="handleUpdateRecordImg"
                @deleRecord="handleDeleteTrafficRecord"
              ></record-list>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </form-dialog>
</template>
<script setup lang="ts">
import { ref } from "vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { useInitForm } from "@/hooks/useCommon";
import FormDialog from "@/components/FormDialog.vue";
import useDown from "@/hooks/useDown";
import { showLoading, hideLoading } from "@/utils/index";
import RecordList from "./recordList.vue";
import {
  completeEnterpriseCarApi,
  getEnterpriseCardInfoApi,
  archiveEnterpriseCarApi
} from "@/api/second";

const emits = defineEmits(["success"]);
// 表单配置
const formConfigList = ref([
  {
    span: 3,
    label: "登记证书",
    prop: "registerCertificate",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "整车出厂合格证",
    prop: "vehicleFactoryCertificate",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "车辆照片(前)",
    prop: "carImgFront",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "车辆照片(后)",
    prop: "carImgBack",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "车辆照片(左)",
    prop: "carImgLeft",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "车辆照片(右)",
    prop: "carImgRight",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "车辆变更记录",
    prop: "carChangeRecord",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "行驶证",
    prop: "drivingLicense",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "道路运输证",
    prop: "roadTransportCertificate",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "技术等级评定表",
    prop: "technicalRatingForm",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "车辆审验记录",
    prop: "carCheckRecord",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "承运人责任保险单",
    prop: "carrierLiabilityPolicy",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "车载定位设备",
    prop: "vehiclePositioningEquipment",
    limit: 1,
    disabled: false,
    isShow: true
  },
  {
    span: 3,
    label: "危货罐体检测合格证",
    prop: "dangerousCargoTankInspectionCertificate",
    limit: 1,
    disabled: false,
    isShow: false
  },
  {
    span: 6,
    label: "客车类型划分及等级评定表",
    prop: "divisionGradeRatingTable",
    limit: 1,
    disabled: false,
    isShow: false
  }
]);
// 车辆信息图片字段
const imgConfig = [
  "registerCertificate",
  "vehicleFactoryCertificate",
  "carImgFront",
  "carImgBack",
  "carImgLeft",
  "carImgRight",
  "drivingLicense",
  "roadTransportCertificate",
  "technicalRatingForm",
  "carChangeRecord",
  "carCheckRecord",
  "carrierLiabilityPolicy",
  "vehiclePositioningEquipment",
  "divisionGradeRatingTable",
  "dangerousCargoTankInspectionCertificate"
];
const curYear = ref(dayjs().format("YYYY-MM-DD HH:mm:ss"));
const handleChangeYear = (e: any) => {
  console.log(e)
  curYear.value = dayjs(e).format("YYYY-MM-DD HH:mm:ss");
  handleReview();
};

// 完善车辆信息
let { formDrawerRef, formRef, form, rules, handleSubmit } = useInitForm({
  isNotTips: true,
  form: {
    carId: "",
    recordYear: "",
    registerCertificate: [],
    vehicleFactoryCertificate: [],
    carImgFront: [],
    carImgBack: [],
    carImgLeft: [],
    carImgRight: [],
    carChangeRecord: [],
    drivingLicense: [],
    roadTransportCertificate: [],
    technicalRatingForm: [],
    carCheckRecord: [],
    carrierLiabilityPolicy: [],
    vehiclePositioningEquipment: [],
    divisionGradeRatingTable: [],
    dangerousCargoTankInspectionCertificate: [],
    cardAdd: {},
    accidentRecordAddList: [
      {
        accidentImgs: [],
        accidentImg: [],
        accidentReason: "",
        mainPerson: "",
        minorPerson: "",
        place: "",
        recordTime: ""
      }
    ]
  },
  rules: {
    // registerCertificate: [
    //   {
    //     required: true,
    //     message: "请上传登记证书",
    //     trigger: "change"
    //   }
    // ],
    // vehicleFactoryCertificate: [
    //   {
    //     required: true,
    //     message: "请上传整车出厂合格证",
    //     trigger: "change"
    //   }
    // ],
    // carImgFront: [
    //   {
    //     required: true,
    //     message: "请上传车辆照片(前)",
    //     trigger: "change"
    //   }
    // ],
    // carImgBack: [
    //   {
    //     required: true,
    //     message: "请上传车辆照片(后)",
    //     trigger: "change"
    //   }
    // ],
    // carImgLeft: [
    //   {
    //     required: true,
    //     message: "请上传车辆照片(左)",
    //     trigger: "change"
    //   }
    // ],
    // carImgRight: [
    //   {
    //     required: true,
    //     message: "请上传车辆照片(右)",
    //     trigger: "change"
    //   }
    // ],
    drivingLicense: [
      {
        required: true,
        message: "请上传行驶证",
        trigger: "change"
      }
    ],
    roadTransportCertificate: [
      {
        required: true,
        message: "请上传道路运输证",
        trigger: "change"
      }
    ],
    technicalRatingForm: [
      {
        required: true,
        message: "请上传技术等级评定表",
        trigger: "change"
      }
    ],
    carCheckRecord: [
      {
        required: true,
        message: "请上传车辆审验记录",
        trigger: "change"
      }
    ],
    carrierLiabilityPolicy: [
      {
        required: true,
        message: "请上传承运人责任保险单",
        trigger: "change"
      }
    ],
    vehiclePositioningEquipment: [
      {
        required: true,
        message: "请上传车载定位设备",
        trigger: "change"
      }
    ],
    dangerousCargoTankInspectionCertificate: [
      {
        required: true,
        message: "请上传危货罐体检测合格证",
        trigger: "change"
      }
    ],
    divisionGradeRatingTable: [
      {
        required: true,
        message: "请上传客车类型划分及等级评定表",
        trigger: "change"
      }
    ]
  },
  createData: completeEnterpriseCarApi,
  success: () => {
    ElMessage.success("完善成功");
    emits("success");
  }
});

// 上传图片
const handleUpdateImg = (val: any, type: any) => {
  form[type] = val;
};
// 上传事故图片
const handleUpdateRecordImg = (e: any, index: number) => {
  form.accidentRecordAddList[index].accidentImgs = e;
};
// 删除交通记录
const handleDeleteTrafficRecord = (val: number) => {
  form.accidentRecordAddList.splice(val, 1);
};

// 添加交通事故记录
const handleAddTraffic = () => {
  form.accidentRecordAddList.push({
    accidentImgs: [],
    accidentImg: [],
    accidentReason: "",
    mainPerson: "",
    minorPerson: "",
    place: "",
    recordTime: ""
  });
};
// 车辆id
const carId = ref("");
// 点击完善后续操作
const handleComplete = (id: any, type: number) => {
  showLoading();
  carId.value = id;
  curYear.value = dayjs().format("YYYY-MM-DD HH:mm:ss");
  // 不同车辆类型上传图片不一样
  handleIsShowConfigList(type);
  // 内容回显
  handleReview();
};
// 回显
const handleReview = async () => {
  try {
    const res: any = await handleGetEnterpriseCardInfo();
    if (res.card) {
      imgConfig.forEach((item) => {
        form[item] = res.card[item]
          ? [
              {
                url: res.card[item]
              }
            ]
          : [];
      });
      form.cardAdd = {
        id: res.card.id
      };
      form.accidentRecordAddList = [];
      const curItem = res.accidentRecordList;
      if (curItem.length) {
        curItem.forEach((item: any) => {
          form.accidentRecordAddList.push({
            accidentImgs: item.accidentImg
              ? [
                  {
                    url: item.accidentImg
                  }
                ]
              : [],
            accidentReason: item.accidentReason,
            mainPerson: item.mainPerson,
            minorPerson: item.minorPerson,
            place: item.place,
            recordTime: item.recordTime
          });
        });
      } else {
        form.accidentRecordAddList = [
          {
            accidentImgs: [],
            accidentImg: [],
            accidentReason: "",
            mainPerson: "",
            minorPerson: "",
            place: "",
            recordTime: ""
          }
        ];
      }
    } else {
      imgConfig.forEach((item) => {
        form[item] = [];
      });
      form.cardAdd = {};
      form.accidentRecordAddList = [
        {
          accidentImgs: [],
          accidentImg: "",
          accidentReason: "",
          mainPerson: "",
          minorPerson: "",
          place: "",
          recordTime: ""
        }
      ];
    }
    (formDrawerRef.value as any).open();
  } finally {
    hideLoading();
  }
};
// 提交
const handleSubmitCar = () => {
  imgConfig.forEach((item) => {
    if (form[item].length > 0) {
      form.cardAdd[item] = form[item][0].url;
    } else {
      form.cardAdd[item] = "";
    }
  });
  for (let item of form.accidentRecordAddList) {
    if (
      item.recordTime ||
      item.place ||
      item.mainPerson ||
      item.minorPerson ||
      item.accidentReason ||
      item.accidentImgs.length > 0
    ) {
      if (
        !(
          item.recordTime &&
          item.place &&
          item.mainPerson &&
          item.minorPerson &&
          item.accidentReason &&
          item.accidentImgs.length > 0
        )
      ) {
        return ElMessage.error("交通事故记录信息不完整");
      }
    }
  }
  form.accidentRecordAddList.forEach((item: any) => {
    if (item.recordTime) {
      item.accidentImg = item.accidentImgs[0].url;
    }
  });
  form.carId = carId.value;
  form.recordYear = curYear.value;
  handleSubmit();
};

// 获取车辆信息
const handleGetEnterpriseCardInfo = async () => {
  return new Promise((resolve) => {
    getEnterpriseCardInfoApi({
      carId: carId.value,
      recordYear: curYear.value
    }).then((res) => {
      resolve(res);
    });
  });
};

// 危货罐体检测合格证和客车类型划分及等级评定表是否显示
const handleIsShowConfigList = (val: number) => {
  if (val === 1) {
    formConfigList.value.forEach((item: any) => {
      if (item.prop === "divisionGradeRatingTable") {
        item.isShow = true;
      }
      if (item.prop === "dangerousCargoTankInspectionCertificate") {
        item.isShow = false;
      }
    });
  } else if (val === 3) {
    formConfigList.value.forEach((item: any) => {
      if (item.prop === "dangerousCargoTankInspectionCertificate") {
        item.isShow = true;
      }
      if (item.prop === "divisionGradeRatingTable") {
        item.isShow = false;
      }
    });
  } else {
    formConfigList.value.forEach((item: any) => {
      if (
        item.prop === "divisionGradeRatingTable" ||
        item.prop === "dangerousCargoTankInspectionCertificate"
      ) {
        item.isShow = false;
      }
    });
  }
};

// 归档
const isLoading = ref(false);
const { downloadFile } = useDown();
const handleArchiveCar = async () => {
  isLoading.value = true;
  try {
    const res: any = await archiveEnterpriseCarApi({
      carId: carId.value,
      year: dayjs(curYear.value).format("YYYY")
    });
    if (res) {
      downloadFile(res as any, "车辆.pdf");
    }
  } finally {
    isLoading.value = false;
  }
};
defineExpose({
  handleSubmitCar,
  handleComplete
});
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 200px);
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
